package com.wardrobe.soa.backend.goods;

import com.wardrobe.dao.goods.GoodsDao;
import com.wardrobe.dao.goods_model.GoodsModelDao;
import com.wardrobe.domain.common.BackEndFromBean;
import com.wardrobe.domain.goods.GoodsBean;
import com.wardrobe.domain.goods.GoodsFromBean;
import com.wardrobe.domain.goods.GoodsShowBean;
import com.wardrobe.domain.goods_model.GoodsModelBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/11/16.
 */
@Service
public class BackGoodsService {
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private GoodsModelDao goodsModelDao;

    public List<GoodsShowBean> getGoodsList(GoodsFromBean fromBean){
        return goodsDao.selectGoodsList(fromBean);
    }
    @Transactional
    public int saveGoods(GoodsBean goodsBean){
        List<Map<String, Object>> attrInfo = goodsBean.getAttrInfo();
        String showPicture = goodsBean.getShowPicture();
        /*int len = showPicture.length();
        if(len > 0){
            goodsBean.setShowPicture(showPicture.substring(0,len-1));
        }*/
        int flag = goodsDao.insertGoods(goodsBean);
        if (flag==1){
            long goodsId = goodsBean.getId();
            long defaultId = 0;
            int length = attrInfo.size();
            if (length>0){
                for (int i = 0; i < length; i++) {
                    Map<String, Object> map = attrInfo.get(i);
                    String price = (String) map.get("price");
                    String type = (String) map.get("type");
                    GoodsModelBean goodsModelBean = GoodsModelBean.builder()
                            .goodsId(goodsId)
                            .type(type)
                            .price(new BigDecimal(price))
                            .build();
                    goodsModelDao.insertGoodsModel(goodsModelBean);
                    if (i == 0) {
                        defaultId = goodsModelBean.getId();
                    }
                }
                BackEndFromBean backEndFromBean = new BackEndFromBean();
                backEndFromBean.setId(goodsId);
                backEndFromBean.setKey("default_id");
                backEndFromBean.setValue(defaultId+"");
                backEndFromBean.setUpdateTime(new Date());
                goodsDao.updateGoods(backEndFromBean);
            }
        }else{
            flag = 2;
        }
        return flag;
    }
    @Transactional
    public int modifyGoods(BackEndFromBean fromBean){
        return goodsDao.updateGoods(fromBean);
    }
    public long countGoods(GoodsFromBean fromBean){
        return goodsDao.countGoods(fromBean);
    }
}
